import numpy as np
from PIL import Image
import matplotlib.pyplot as plt


def sliding_window_he(image_path, window_size=16, stride=4):
    """
    在HSV空间对V通道应用滑动窗口HE，然后合并回RGB空间

    参数:
    - image_path: 输入图像路径
    - window_size: 滑动窗口大小
    - stride: 窗口滑动步长
    """
    # 读取图像并转换到HSV空间
    img = Image.open(image_path).convert('HSV')
    img_array = np.array(img, dtype=np.uint8)
    height, width, _ = img_array.shape

    # 分离HSV通道
    h, s, v = img_array[:, :, 0], img_array[:, :, 1], img_array[:, :, 2]

    # 创建用于累积处理结果和计数的数组
    v_result_sum = np.zeros_like(v, dtype=np.float64)
    result_count = np.zeros_like(v, dtype=np.int32)

    # 滑动窗口处理V通道
    for y in range(0, height - window_size + 1, stride):
        for x in range(0, width - window_size + 1, stride):
            # 提取当前窗口
            window = v[y:y + window_size, x:x + window_size]

            # 对窗口内像素进行直方图均衡化
            hist, bins = np.histogram(window.flatten(), 256, [0, 256])
            cdf = hist.cumsum()
            cdf_m = np.ma.masked_equal(cdf, 0)
            cdf_m = (cdf_m - cdf_m.min()) * 255 / (cdf_m.max() - cdf_m.min())
            cdf = np.ma.filled(cdf_m, 0).astype('uint8')

            # 应用均衡化映射到窗口
            window_eq = cdf[window]

            # 累积处理结果
            v_result_sum[y:y + window_size, x:x + window_size] += window_eq
            result_count[y:y + window_size, x:x + window_size] += 1

    # 计算V通道的平均值（避免除以零）
    result_count = np.maximum(result_count, 1)
    v_processed = (v_result_sum / result_count).astype(np.uint8)

    # 合并处理后的V通道与原始H、S通道
    hsv_processed = np.stack([h, s, v_processed], axis=2)

    # 转回RGB空间
    rgb_processed = Image.fromarray(hsv_processed, mode='HSV').convert('RGB')
    rgb_processed_array = np.array(rgb_processed)

    # 显示原始图像和处理后的图像
    plt.figure(figsize=(12, 6))

    plt.subplot(1, 2, 1)
    plt.imshow(np.array(img.convert('RGB')))
    plt.title('原始图像')
    plt.axis('off')

    plt.subplot(1, 2, 2)
    plt.imshow(rgb_processed_array)
    plt.title(f'HSV空间滑动窗口HE (窗口={window_size}, 步长={stride})')
    plt.axis('off')

    plt.tight_layout()
    plt.show()

    return rgb_processed_array
sliding_window_he("D:\jvnhenghua\\test.jpg", window_size=25, stride=5)